<template>
  <div class="box">
    <!-- 搜索区域 -->
    <el-card class="search">
      搜索列表 🍓🍇🍈🍉
      <el-input type="text" v-model="searchFrom.keyword" placeholder="请输入关键字..." style="width: 300px; margin-left: 10px">
        <el-button @click="getList(searchFrom.keyword)" slot="append" type="primary" icon="el-icon-search"></el-button>
      </el-input>
      <el-button @click="addOrder" class="btn-add" icon="el-icon-plus" size="medium" round>添加</el-button>
    </el-card>
    <!-- 订单列表 -->
    <el-card>
      <common-table :tableData="tableDate" :tableLabel="tableLabel" :config="config" @changePage="getList()" @handleSizeChange="getList()" @edit="editOrder" @del="delOrder"> </common-table>
    </el-card>
    <!-- 添加或更新订单对话框 -->
    <el-dialog :title="operateType === 'add' ? '新增订单' : '更新订单'" :visible.sync="isShow">
      <el-form :model="operateForm" :rules="formRules" ref="operateFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item v-for="item in opertateFormLabel" :key="item.label" :label="item.label" :prop="item.model">
          <el-select v-if="item.type === 'select'" v-model="operateForm[item.model]">
            <el-option v-for="item2 in item.opts" :key="item2.value" :label="item2.label" :value="item2.value"></el-option>
          </el-select>
          <el-input v-if="item.type === 'input'" v-model="operateForm[item.model]" :placeholder="'请输入' + item.label"></el-input>
          <el-date-picker v-if="item.type === 'datetime'" v-model="operateForm[item.model]" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择日期"></el-date-picker>
          <!-- 地址 -->
          <el-cascader v-if="item.type === 'cascader'" placeholder="请选择地址" :options="options" v-model="selectOptions" @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item class="btn">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '../../components/table/index.vue'
import { regionData, CodeToText } from 'element-china-area-data'
export default {
  name: 'User',
  components: {
    CommonTable
  },
  data() {
    return {
      //表中的数据
      tableDate: [],
      //表头
      tableLabel: [
        {
          prop: 'orderId',
          label: '订单编号',
          width: 300
        },
        {
          prop: 'orderPrice',
          label: '订单价格',
          width: 180
        },
        {
          prop: 'isPay',
          label: '是否付款',
          width: 180
        },
        {
          prop: 'isSend',
          label: '是否发货',
          width: 180
        },
        {
          prop: 'addr',
          label: '发货地址',
          width: '300'
        },
        {
          prop: 'time',
          label: '下单时间',
          width: 200
        }
      ],
      //分页
      config: {
        page: 1, //当前页数
        pagesize: 20, //每页显示个数
        total: 30
      },
      // 搜索关键字
      searchFrom: {
        keyword: ''
      },

      // 添加商品对话框
      operateType: 'add',
      isShow: false, //弹框的显示与隐藏
      opertateFormLabel: [
        {
          model: 'orderId',
          label: '订单编号',
          type: 'input'
        },
        {
          model: 'orderPrice',
          label: '订单价格',
          type: 'input'
        },
        {
          model: 'isPay',
          label: '是否付款',
          type: 'select',
          opts: [
            {
              label: '已付款',
              value: '1'
            },
            {
              label: '未付款',
              value: '-1'
            },
            {
              label: '待付款',
              value: '0'
            }
          ]
        },
        {
          model: 'isSend',
          label: '是否发货',
          type: 'select',
          opts: [
            {
              label: '是',
              value: true
            },
            {
              label: '否',
              value: false
            }
          ]
        },
        {
          model: 'addr',
          label: '发货地址',
          type: 'cascader'
        },
        {
          model: 'time',
          label: '下单时间',
          type: 'datetime'
        }
      ],
      operateForm: {
        orderId: '',
        orderPrice: '',
        isPay: '',
        isSend: '',
        time: [new Date(new Date()), new Date(new Date())],
        addr: ''
      },
      //校验规则
      formRules: {
        orderId: [{ required: true, message: '请输入订单编号', trigger: ['blur'] }],
        orderPrice: [{ required: true, message: '请输入订单价格', trigger: 'blur' }],
        isPay: [{ type: 'number', required: true, message: '请选择是否付款', trigger: ['blur', 'change'], transform: value => Number(value) }],
        isSend: [{ type: 'number', required: true, message: '请选择是否发货', trigger: ['blur', 'change'], transform: value => Number(value) }],
        time: [{ type: 'date', required: true, message: '请输入下单时间', trigger: ['blur', 'change'], transform: value => Number(value) }],
        addr: [{ type: 'regexp', required: true, message: '请选择省市区/县', trigger: ['change'], transform: value => Number(value) }]
      },
      options: regionData, //地址选项
      selectOptions: []
    }
  },
  methods: {
    //选择地址
    handleChange(value) {
      this.select = value
      if (isNaN(value[0])) {
        for (let i = 0; i < this.select.length; i++) {
          this.selectOptions[i] = this.select[i]
        }
      } else {
        for (let i = 0; i < this.select.length; i++) {
          this.selectOptions[i] = CodeToText[this.select[i]]
        }
      }
      console.log(this.selectOptions, 'selectOptions')
      this.operateForm.addr = this.selectOptions.join(' ')
    },
    //点击确定
    confirm() {
      this.$refs.operateFormRef.validate(async valid => {
        if (!valid) return
        if (this.operateType === 'add') {
          this.selectOptions = []
          const { data: res } = await this.$http.post('/order/add', this.operateForm)
          if (res.code === 201) {
            this.$message.success('添加订单成功！')
            this.isShow = false
            this.getList()
          } else {
            this.$message.error('添加订单失败！')
          }
        }
        if (this.operateType === 'edit') {
          this.selectOptions = []
          const { data: res } = await this.$http.post('/order/edit', this.operateForm)
          if (res.code === 201) {
            this.$message.success('修改商品成功！')
            this.isShow = false
            this.getList()
          } else {
            this.$message.error('修改商品失败！')
          }
        }
      })
    },
    //添加订单
    addOrder() {
      this.isShow = true
      this.operateType = 'add'
      this.operateForm = {
        orderId: '',
        orderPrice: '',
        isPay: '',
        isShip: '',
        addr: '',
        time: ''
      }
      // this.$router.push('/addgoods')
    },
    //修改订单
    editOrder(row) {
      this.operateType = 'edit'
      this.isShow = true
      this.operateForm = row
    },
    //根据订单编号查找商品
    async getList(orderId = '') {
      orderId ? (this.config.page = 1) : ''
      orderId ? (this.config.pagesize = 20) : ''
      const { data: res } = await this.$http.get('/order/getorder', { params: { orderId, page: this.config.page, pagesize: this.config.pagesize } })
      if (res.code === 200) {
        this.tableDate = res.data.map(item => {
          item.isSend = item.isSend ? '是' : '否'
          return item
        })
        this.config.total = res.count
      }
    },
    //删除商品
    delOrder(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const id = row.orderId
          const { data: res } = await this.$http.post('/order/del', id)
          if (res.code === 200) {
            this.$message.success('删除订单成功！')
            this.getList()
          } else {
            this.$message.error('删除订单失败！')
          }
        })
        .catch(action => {
          if (action === 'cancel') this.$message.info('已取消删除')
        })
    },
    /* 上传商品图片 */
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style lang="less">
.search {
  margin-bottom: 10px;
  .el-card__body,
  .el-main {
    padding: 12px 20px;
  }
  .btn-add {
    float: right;
    margin-left: 20px;
    background-color: #2d51e6;
    color: #fff;
  }
}
</style>
